package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetMealService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 报表
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetMealService setMealService;

    @Reference
    private ReportService reportService;

    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        //使用模拟数据测试数据格式是否正确
        /*Map<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();
        months.add("2020.03");
        months.add("2020.04");
        months.add("2020.05");
        months.add("2020.06");
        months.add("2020.07");
        months.add("2020.08");
        map.put("months", months);

        List<Integer> memberCount = new ArrayList<>();
        memberCount.add(150);
        memberCount.add(120);
        memberCount.add(130);
        memberCount.add(160);
        memberCount.add(170);
        memberCount.add(100);
        map.put("memberCount", memberCount);*/

        //所有有人注册的月份的当月注册人数
        Map<String, Object> map1 = memberService.getMonthsAndMCount();

        Map<String, Object> map2 = new HashMap<>();
        List<String> months = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();//获得日历对象，模拟时间就是当前时间
        //计算过去一年的12个月
        calendar.add(Calendar.MONTH, -12);//获得当前时间往前推12个月的时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);//获得当前时间往后推一个月日期
            Date date = calendar.getTime();
            months.add(format.format(date));//这里不应该在循环中new对象(改了,一开始是在这里new SimpleDateFormat对象的)
            //还有,SimpleDateFormat不能定义为static对象,因为它线程不安全(记住)
        }
        map2.put("months", months);

        List<Integer> memberCount = memberService.findMemberCountByMonths(months);
        map2.put("memberCount", memberCount);
        //return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map2);

        return new Result(true, "获取数据成功", map2);
    }

    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        List<String> setmealNames = new ArrayList<>();
        List<Map<String, Object>> setmealCount = new ArrayList<>();


        //模拟一些数据处理来
        /*
        setmealNames.add("套餐一");
        setmealNames.add("套餐二");
        setmealNames.add("套餐三");
        setmealNames.add("套餐四");
        */

        /*
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        Map<String, Object> map3 = new HashMap<>();
        Map<String, Object> map4 = new HashMap<>();
        map1.put("name", "套餐一");
        map1.put("value", 10);
        map2.put("name", "套餐二");
        map2.put("value", 20);
        map3.put("name", "套餐三");
        map3.put("value", 30);
        map4.put("name", "套餐四");
        map4.put("value", 40);
        setmealCount.add(map1);
        setmealCount.add(map2);
        setmealCount.add(map3);
        setmealCount.add(map4);
        */

        try {
            setmealNames = setMealService.findAllSetMealNames();
            setmealCount = setMealService.findOrderData();

            Map<String, Object> result = new HashMap<>();
            result.put("setmealNames", setmealNames);
            result.put("setmealCount", setmealCount);

            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, result);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }

    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.QUERY_SETMEALLIST_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEALLIST_FAIL);
        }
    }

    //导出Excel
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> result = reportService.getBusinessReportData();
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) result.get("hotSetmeal");

            String path = request.getSession().getServletContext().getRealPath("template")
                    + File.separator + "report_template.xlsx";

            //基于提供的模板文件创建一个新的表格对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(path)));

            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for (Map map : hotSetmeal) {//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //使用输出流进行表格下载
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式下载
            excel.write(outputStream);

            outputStream.flush();
            outputStream.close();
            excel.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}
